﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using ShortCutLib;
using System.Windows.Forms;
using System.Diagnostics;

namespace AppInitRunner
{
    internal class Runner
    {
        private static string ShotCutFolder = "ShotCutFolder";

        /// <summary>
        /// 应用程序启动间隔.默认1分钟启动一个
        /// </summary>
        private const int ApplicationStartInterval = 1 * 60 * 1000;

        public Runner()
        {

        }

        /// <summary>
        /// 运行进程
        /// </summary>
        public void RunApplications()
        {
            try
            {
                //程序启动后暂停一分钟.
                System.Threading.Thread.Sleep(ApplicationStartInterval);

                //string[] shotCuts = Directory.GetFiles(Environment.CurrentDirectory + Path.DirectorySeparatorChar + Runner.ShotCutFolder);
                string[] shotCuts =  Directory.GetFiles(@"F:\05.Work\WorkOfTest08Collections\AppInitRunner\bin\Debug\ShotCutFolder");
                ShortCut sc = new ShortCut();

                foreach (string shotCut in shotCuts)
                {
                    sc.LnkPath = shotCut;
                    sc.ResolveLink();
                    string appName = Path.GetFileNameWithoutExtension(sc.FilePath);
                    if (!this.IsProcessRunning(appName))
                    {
                        this.StartProcessByFileName(sc.FilePath);
                        System.Threading.Thread.Sleep(ApplicationStartInterval);
                    }

                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                MessageBox.Show(e.Message);
            }
        }

        /// <summary>
        /// 进程是否在运行
        /// </summary>
        /// <param name="appName"></param>
        /// <returns></returns>
        private bool IsProcessRunning(string appName)
        {
            Process[] processes = Process.GetProcessesByName(appName);
            if (processes != null && processes.Length > 0 && processes[0].HasExited == false)
                return true;
            else
                return false;

        }

        /// <summary>
        /// 启动由路径指定的相应进程
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private bool StartProcessByFileName(string fileName)
        {
            try
            {
                Process.Start(fileName);
                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return false;
            }
        }
    }
}
